#include "rtthread.h"
#include <stdio.h>
#include <stdarg.h>
#include <string.h>
#include <stdint.h>
#include "rtconfig.h"
#include "usart.h"

static char puts_buff[RT_CONSOLEBUF_SIZE + 1] = {0};

void rt_hw_console_puts(char *str, uint32_t size)
{
    HAL_UART_Transmit(&huart1, (const unsigned char *)str, size, 5000);
}

char rt_hw_console_getchar(void)
{
	char ch = -1;
	HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 5000);
	return ch;
}

int rt_kprintf(const char *fmt, ...)
{
    // char aaa[] = "\r";
    // rt_hw_console_puts(aaa, strlen(aaa));

	va_list args;
    va_start(args, fmt);
    memset(puts_buff, 0, sizeof(puts_buff));
    vsnprintf(puts_buff, sizeof(puts_buff) - 1, fmt, args);
    va_end(args);

    uint32_t len = strlen(puts_buff);
    if (len >= 2) {
        if (puts_buff[len - 1] == '\n' && puts_buff[len - 2] != '\r') {
            puts_buff[len - 1] = '\r';
            puts_buff[len] = '\n';
            puts_buff[len + 1] = '\0';
        }
    } else if (len == 1 && puts_buff[0] == '\n') {
		puts_buff[0] = '\r';
		puts_buff[1] = '\n';
		puts_buff[2] = '\0';
	}
    
    rt_hw_console_puts(puts_buff, strlen(puts_buff));
}

void rt_show_version(void)
{
	char str[] = "msh demo\r\n";
	rt_hw_console_puts(str, strlen(str));
}